<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="addrole">添加角色</el-button>
      </div>
      <el-table :data="list">
        <el-table-column
          align="center"
          label="角色"
          width="200"
          prop="name"
        >
          <!-- 条件判断 -->
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRole.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="启用"
          width="200"
          prop="state"
        >
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRole.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="描述"
          prop="description"
        >
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRole.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
        >
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button
                size="mini"
                type="primary"
                @click="confirmUpdate(row)"
              >确定</el-button>
              <el-button
                size="mini"
                @click="closeEdit(row)"
              >取消</el-button>
            </template>
            <template v-else>
              <el-button
                size="mini"
                type="text"
              >分配权限</el-button>
              <el-button
                size="mini"
                type="text"
                @click="editrole(row)"
              >编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="delrole(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="height: 60px;" align="middle">
        <el-pagination
          small
          layout="prev, pager, next"
          :total="total"
          :current-page="page"
          :page-size="pagesize"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <el-dialog
      title="新增角色"
      :visible.sync="isShowDialog"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="formList" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formList.name" style="width: 300px;" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="formList.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formList.description" type="textarea" :rows="3" style="width: 300px;" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="confirm">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { delRole, getaddRole, getrole, updateRole } from '@/api/role'

export default {
  name: 'Role',
  data() {
    return {
      page: 1,
      pagesize: 5,
      total: 0,
      list: [],
      isShowDialog: false,
      formList: {
        name: '',
        description: '',
        state: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getrole({
        page: this.page,
        pagesize: this.pagesize
      })
      console.log(res)
      this.list = res.rows
      this.total = res.total
      // 数据响应式的问题  数据变化 视图更新
      // 添加的动态属性 不具备响应式特点
      // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        // 缓存数据
        this.$set(item, 'editRole', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 更新角色
    async confirmUpdate(row) {
      // 检查必填
      if (row.editRole.name && row.editRole.description) {
        // 更新接口
        await updateRole({
          ...row.editRole,
          id: row.id
        })
        // 提示用户
        this.$message.success('更新成功')
        // 退出编辑，重新加载数据
        // Object.assign(目标对象, 源对象1, 源对象2,....) 浅拷贝 - 克隆 / 合并
        // 将一个或者多个源对象中属性复制到目标对象
        Object.assign(row, {
          ...row.editRole,
          isEdit: false
        })
      }
    },
    editrole(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRole.name = row.name
      row.editRole.state = row.state
      row.editRole.description = row.description
    },
    closeEdit(row) {
      row.isEdit = false
    },
    handleCurrentChange(value) {
      this.page = value
      this.getRoleList()
    },
    addrole() {
      this.isShowDialog = true
    },
    close() {
      this.$refs.form.resetFields() // 清空表单
      this.isShowDialog = false
    },
    async confirm() {
      await this.$refs.form.validate() // 校验表单
      await getaddRole(this.formList) // 调用接口
      this.$message.success('添加角色成功') // 提示用户
      this.getRoleList() // 重新加载数据
      this.close() // 关闭弹窗
    },
    async delrole(id) {
      await delRole(id)
      this.$message.success('删除成功')
      // 如果当前页只有最后一条数据删除之后页码减1，并且不是最后一页
      if (this.list.length === 1 && this.page !== 1) {
        this.page--
      }
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
